import '../../public.dart';

class RegistPage extends StatefulWidget {
  const RegistPage({super.key});

  @override
  State<RegistPage> createState() => _RegistPageState();
}

class _RegistPageState extends State<RegistPage> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  String? phone; // 手机号
  String? email; // 邮箱
  String? verifyCode; // 验证码
  String? password;
  String? passwordAgin;
  String? invitationCode; // 邀请码
  String? userName; // 用户名
  String? fullName; // 用户全名
  bool isLoading = false; // 加载状态
  bool _isObscure = true; // 密码可见性
  bool _isAginObscure = true; // 确认密码可见性
  int _countdown = 0; // 验证码倒计时
  Timer? _timer; // 倒计时定时器
  bool _agreeTerms = false; // 同意条款复选框

  // 注册方法
  void regist() async {
    final loginForm = formKey.currentState;
    if (loginForm!.validate() && _agreeTerms) {
      loginForm.save();

      // 设置加载状态
      setState(() {
        isLoading = true;
      });

      try {
        // 构建注册参数
        ClientUserRegistDto registParams = ClientUserRegistDto(
          email: email!,
          fullName: fullName!,
          password: password!,
          phone: phone!,
          referral: invitationCode,
          userName: userName!,
          verifyCode: verifyCode!,
        );

        // 调用注册API
        await RegisterApi.create_2(registParams);

        // 注册成功提示
        Toast.show('Registration successful!');

        // 跳转到登录页面
        RouterHelper.navigator.pushNamedAndRemoveUntil(
          Routers.login,
          (route) => false,
        );
      } catch (e) {
        // 处理错误
        Toast.show('Registration failed: $e');
      } finally {
        // 取消加载状态
        setState(() {
          isLoading = false;
        });
      }
    } else if (!_agreeTerms) {
      Toast.show('Please agree to Terms of Use and Privacy Policy');
    }
  }

  // 获取邮箱验证码
  void getEmailCode() {
    if (email == null || email!.isEmpty) {
      Toast.show('Please enter your email address');
      return;
    }

    // 验证邮箱格式
    if (!RegexUtil.isEmail(email!)) {
      Toast.show('Please enter a valid email address');
      return;
    }

    // 显示加载提示
    Toast.show('Sending verification code...');

    // 模拟发送验证码的网络请求
    RegisterApi.getVerifyCodeByEmail(EmailDto(receiveEmail: email!))
        .then((_) {
          // 模拟发送成功
          Toast.show('Verification code sent to $email');

          // 开始倒计时
          setState(() {
            _countdown = 60;
          });

          _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
            if (mounted) {
              setState(() {
                if (_countdown > 0) {
                  _countdown--;
                } else {
                  _timer?.cancel();
                }
              });
            } else {
              timer.cancel();
            }
          });
        })
        .catchError((e) {
          Toast.show('Failed to send verification code: $e');
        });
  }

  @override
  void dispose() {
    // 清理定时器
    if (_timer != null && _timer!.isActive) {
      _timer!.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ListView(
        padding: const EdgeInsets.symmetric(horizontal: 30),
        children: [
          const SizedBox(height: 60),
          wellCome(context),
          Form(
            key: formKey,
            child: Column(
              children: [
                userNameItem(context),
                passwordItem(context),
                passwordAginItem(context),
                emailItem(context),
                codeItem(context),
                phoneItem(context),
                fullNameItem(context),
                invitationCodeItem(context),
                const SizedBox(height: 24),
                // 同意条款复选框
                CheckboxListTile(
                  title: RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(
                          text: 'By creating an account, you agree to our ',
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                        ),
                        TextSpan(
                          text: 'Terms of Service',
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              print('Terms of Service clicked');
                            },
                        ),
                        TextSpan(
                          text: ' and ',
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                        ),
                        TextSpan(
                          text: 'Privacy Policy',
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              print('Privacy Policy clicked');
                            },
                        ),
                      ],
                    ),
                  ),
                  value: _agreeTerms,
                  onChanged: (bool? value) {
                    setState(() {
                      _agreeTerms = value!;
                    });
                  },
                  controlAffinity: ListTileControlAffinity.leading,
                  activeColor: Colors.black,
                  contentPadding: EdgeInsets.zero,
                  dense: true,
                ),
                const SizedBox(height: 24),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 0),
                  child: ElevatedButton(
                    onPressed: regist,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.black,
                      minimumSize: const Size(double.infinity, 50),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(4),
                      ),
                      elevation: 0,
                    ),
                    child: isLoading
                        ? const CircularProgressIndicator(
                            color: Colors.white,
                            strokeWidth: 2,
                          )
                        : const Text(
                            'CREATE ACCOUNT',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 20),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "Already a member? ",
                        style: TextStyle(color: Colors.grey[600], fontSize: 14),
                      ),
                      GestureDetector(
                        onTap: () {
                          RouterHelper.navigator.pushReplacementNamed(
                            Routers.login,
                          );
                        },
                        child: const Text(
                          "Sign in.",
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget wellCome(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(bottom: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () => RouterHelper.navigator.pop(),
            child: Icon(
              Icons.chevron_left,
              color: Colors.grey,
              size: ScreenUtil.setSp(32).toDouble(),
            ),
          ),
          const SizedBox(height: 20),
          const Text(
            'CREATE YOUR ACCOUNT',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          const SizedBox(height: 10),
          Text(
            'Fill in the form below to get started with your account',
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),
          ),
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget phoneItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        inputFormatters: <TextInputFormatter>[
          // LengthLimitingTextInputFormatter(11), //限制长度
          FilteringTextInputFormatter.digitsOnly,
        ],
        // 键盘回车键
        keyboardType: TextInputType.number,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        validator: validatePhone,
        onSaved: (value) => phone = value,
        onChanged: (value) => phone = value,
        decoration: getCommonInputDecoration(
          hintText: "Enter your mobile phone number",
          labelText: "Mobile",
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  Widget passwordItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        obscureText: _isObscure,
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: validatePassword,
        onSaved: (value) => password = value,
        onChanged: (value) => password = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Please enter your password",
          labelText: "Password",
          suffixIcon: IconButton(
            icon: Icon(
              _isObscure ? Icons.visibility : Icons.visibility_off,
              color: Colors.grey[500],
            ),
            onPressed: () {
              setState(() {
                _isObscure = !_isObscure;
              });
            },
          ),
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  // 邮箱输入项
  Widget emailItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.emailAddress,
        validator: validateEmail,
        onSaved: (value) => email = value,
        onChanged: (value) => email = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Enter your email address",
          labelText: "Email",
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  // 验证码输入项
  Widget codeItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.number,
        inputFormatters: <TextInputFormatter>[
          FilteringTextInputFormatter.digitsOnly,
        ],
        validator: validateVerificationCode,
        onSaved: (value) => verifyCode = value,
        onChanged: (value) => verifyCode = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Enter verification code",
          labelText: "Verification Code",
          suffixIcon: GestureDetector(
            onTap: _countdown == 0 ? getEmailCode : null,
            child: Container(
              width: 100,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(right: 15),
              child: Text(
                _countdown == 0 ? 'Get Code' : '${_countdown}s',
                style: TextStyle(
                  color: _countdown == 0 ? Colors.black : Colors.grey[400],
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  // 用户名输入项
  Widget userNameItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: validateUserName,
        onSaved: (value) => userName = value,
        onChanged: (value) => userName = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Enter your account name",
          labelText: "Account Name",
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  // 全名输入项
  Widget fullNameItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: validateFullName,
        onSaved: (value) => fullName = value,
        onChanged: (value) => fullName = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Enter your full name",
          labelText: "Full Name",
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  // 邀请码输入项
  Widget invitationCodeItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: (value) {
          // 邀请码可选，不强制要求
          return null;
        },
        onSaved: (value) => invitationCode = value,
        onChanged: (value) => invitationCode = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Enter invitation code (optional)",
          labelText: "Invitation Code",
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }

  Widget passwordAginItem(BuildContext context) {
    return buildFormItem(
      TextFormField(
        obscureText: _isAginObscure,
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: (value) =>
            validateConfirmPassword(value ?? '', password ?? ''),
        onSaved: (value) => passwordAgin = value,
        onChanged: (value) => passwordAgin = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: "Confirm your password",
          labelText: "Confirm Password",
          suffixIcon: IconButton(
            icon: Icon(
              _isAginObscure ? Icons.visibility : Icons.visibility_off,
              color: Colors.grey[500],
            ),
            onPressed: () {
              setState(() {
                _isAginObscure = !_isAginObscure;
              });
            },
          ),
        ).copyWith(fillColor: Colors.grey.shade50),
      ),
    );
  }
}
